<template>
  <div class="paren">
    <Userdetails 
      v-if="showDetails" 
      :userData="selectedUser"
      @back="handleBack"
      @status-updated="handleStatusUpdated"
    />
    <!-- 数据 -->
    <template v-else>
      <div class="table-wrapper">
        <el-table 
          :data="currentTableData"
          height="100%"
          :header-cell-style="{ color: 'rgb(82,85,96)', textAlign: 'center' }"
          :cell-style="cellStyle"
        >
          <el-table-column prop="id" label="Order ID" show-overflow-tooltip></el-table-column>
          <el-table-column prop="model" label="Model" show-overflow-tooltip></el-table-column>
          <el-table-column prop="dealer" label="Dealer" show-overflow-tooltip></el-table-column>
          <el-table-column prop="faultPart" label="Fault Part" show-overflow-tooltip ></el-table-column>
          <el-table-column prop="createTime" label="Create Time" show-overflow-tooltip width="auto">
            <template #default="{row}">
              <div class="date-part">{{ formatDate(row.createTime) }}</div>
              <div class="time-part">{{ formatTime(row.createTime) }}</div>
            </template>
          </el-table-column>

          <el-table-column prop="state" label="Status">
            <template #default="{ row }">
              <span :style="{ color: states[row.state].color }">
                {{ states[row.state].text }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="Details">
            <template #default="scope">
              <el-button @click="showUserDetails(scope.row)">View</el-button>
            </template>
            
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-footer">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="tableData.length">
        </el-pagination>
        <div class="add-button">
          <el-button type="primary" @click="handleAdd">Add</el-button>
        </div>
      </div>
      <!-- 添加对话框 -->
      <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px" style="padding: 20px 40px;" class="large-dialog">
        <el-form :model="formData">
          <!-- model dealer -->
          <div class="form-row">
            <el-form-item label="model" required class="form-item-half">
              <el-select 
                v-model="formData.model" 
                placeholder="Select model"
                size="large"
                clearable
                @focus="getModelList"
              >
                <el-option
                  v-for="item in modelList"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="dealer" required class="form-item-half">
              <el-input v-model="formData.dealer" :disabled="true"></el-input>
            </el-form-item>
          </div>
          <!-- country city -->
          <div class="form-row">
            <el-form-item label="country" required class="form-item-two-thirds">
              <el-select
                v-model="formData.country"
                filterable
                placeholder="Select a country"
                size="large"
                @focus="getCountry"
              >
                <el-option
                  v-for="item in countryList"
                  :key="item"
                  :label="item.en"
                  :value="item.en"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="city" class="form-item-one-third">
              <el-input v-model="formData.city"></el-input>
            </el-form-item>
          </div>
          <!-- account name -->
          <div class="form-row">
            <el-form-item label="account" required class="form-item-two-thirds">
              <el-input v-model="formData.account"></el-input>
            </el-form-item>
            <el-form-item label="name" required class="form-item-one-third">
              <el-input v-model="formData.nickName"></el-input>
            </el-form-item>
          </div>
            
          <el-form-item label="Fault Part" required>
            <el-select
              v-model="selectedParts"
              value-key="partName"
              multiple
              placeholder="Select fault part"
              style="width: 100%"
              size="large"
              @focus="loadFaultParts"
              @change="handleFaultPartChange"
              :disabled="!formData.model"
            >
              <el-option
                v-for="(part,index) in faultPartsOptions"
                :key="index"
                :label="part.partName"
                :value="part"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="Reason" required>
            <el-select
              v-model="formData.reason"
              multiple
              placeholder="Select reason"
              style="width: 100%"
              size="large"
              @focus="loadReasons"
              :disabled="!formData.faultPart || formData.faultPart.length === 0"
            >
              <el-option
                v-for="(reason,index) in reasonsOptions"
                :key="index"
                :label="reason"
                :value="reason"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="Part Missing">
            <el-input v-model="formData.partMissing"></el-input>
          </el-form-item>
          <el-form-item label="image">
            <div class="upload-img-btn">
              <div v-for="index in 3" style="position: relative;width: 180px;height: 180px;">
                <input id="upload" type="file" accept="image/*" class="upload-input" @change="onFileChange($event,index-1)"/>
                <img :src="images.length>index-1?images[index-1]['src']:selectedImage" class="img-scan" mode="aspectFit"/>
                <img v-if="images.length>index-1" src="../../assets/images/icon_del.png" class="img-del" @click="onImageDel(index-1)">
              </div>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">Cancel</el-button>
            <el-button type="primary" @click="handleConfirm">confirm</el-button>
          </span>
        </template>
      </el-dialog>
    </template>
  </div>

</template>

<script setup name="Repair">
  import { ref,onMounted,computed,watch } from 'vue';
  import axios from 'axios';
  import { ElMessage } from 'element-plus';
  import {compressImg} from '../../utils';
  import Userdetails from '../details/UserDetails.vue';
  import { useManageStore } from '../../store/manageStore';
  import { useLoading } from '../../utils/loading';
  const manageStore = useManageStore()
  const { showLoading, hideLoading } = useLoading();
  const BASE_URL = import.meta.env.VITE_API_URL
  
  //响应式数据
  const dealer = computed(() => manageStore.dealer)
  const userId = computed(() => manageStore.userId)
  const account = computed(() => manageStore.account)
  const nickName = computed(() => manageStore.name)
  const tableData = ref([]);
  const modelList = ref([]);
  // 分页相关变量currentPage、pageSize
  const currentPage = ref(1);
  const pageSize = ref(20);

  const showDetails = ref(false);
  const selectedUser = ref(null);

  const dialogVisible = ref(false);
  const dialogTitle = ref('Add data');
  const selectedImage = new URL('../../assets/images/image_add_sel.png',import.meta.url).href;
  const images = ref([]);
  const faultPartsOptions = ref([]);
  const selectedFaultTypes = ref([]);

  const reasonsOptions = ref([]);
  const selectedParts = ref([]);
  const countryList = ref([]);

  const formData = ref({
    model: '',
    dealer: dealer.value,
    userId: userId.value,
    nickName: nickName.value,
    country: '',
    city: '',
    account: account.value,
    faultPart: '',
    reason: '',
    partMissing: '',
    description: '',
    partDamaged: '',
    noResponse: '',
    images: '',
  });
  onMounted(() => {
    fetchData();
  })
  // 监听型号变化时清空相关选项
  watch(() => formData.value.model, (newVal) => {
    if (!newVal) {
      faultPartsOptions.value = [];
      reasonsOptions.value = [];
      formData.value.faultPart = [];
      formData.value.reason = [];
    }
  });

  // 监听故障部件变化时清空已选原因
  watch(() => formData.value.faultPart, (newVal) => {
    if (!newVal || newVal.length === 0) {
      reasonsOptions.value = [];
      formData.value.reason = [];
    }
  });
  const states = {
    0:{text:'Unhandled',color:'rgb(129, 133, 129)'},
    1:{text:'Processing',color:'rgb(32, 146, 246)'},
    2:{text:'Processed',color:'rgb(0, 200, 50)'},
  }
   // 获取数据的函数
  const fetchData = async () => {
    try {
      showLoading('Loading data...');
      const response = await axios.get(`${BASE_URL}manage/afterSaleList`,{
        params:{
          dealer: dealer.value,
          page: 0,
          pageSize: 100
        }
      })
      const resultData = response.data;
      
      tableData.value = resultData.data.users;
    } catch (error) {
      ElMessage.error('Failed to obtain data');
    } finally {
      hideLoading();
    }
  }
  //获取modelList
  const getModelList = async () => {
    try {
      showLoading('Loading models...');
      const res = await axios.get(`${BASE_URL}manage/modelList`,{
        params: {
          dealers: dealer.value,
        }
      })
      modelList.value = res.data.data;
      
    }catch(error) {
      ElMessage.error('Failed to load models');
    }finally {
      hideLoading();
    }
  }
  
  //获取faultParts
  const loadFaultParts = async() => {
    showLoading('Loading parts...');
    try {
      const res = await axios.get(`${BASE_URL}afterSales/queryModel`,{
        params: {
          model: formData.value.model
        }
      })
      faultPartsOptions.value = res.data.data
        .filter(item => item.partName)
        .map(item => ({
          partName: item.partName,
          faultType: item.faultType
      }));
    }catch(error) {
      ElMessage.error('Failed to obtain the faulty component');
    }finally {
      hideLoading();
    }
  }
  const handleFaultPartChange = (selectedParts) => {
    // 更新表单数据和故障类型
    formData.value.faultPart = selectedParts.map(p => p.partName);
    selectedFaultTypes.value = selectedParts.map(p => p.faultType);
    // 清空已选原因（当部件变更时）
    formData.value.reason = [];
    reasonsOptions.value = [];
  };
  //获取故障部件
  const loadReasons = async() => {
    try {
      showLoading('Loading reasons...');
      const res = await axios.get(`${BASE_URL}afterSales/queryFaults`,{
        params: {
          types:selectedFaultTypes.value.join(',')
        }
      })
      if (typeof res.data.data === 'string') {
        reasonsOptions.value = res.data.data.split(',').map(s => s.trim());
      } else if (Array.isArray(res.data.data)) {
        reasonsOptions.value = res.data.data;
      } else {
        reasonsOptions.value = [];
      }
    }catch(error) {
      ElMessage.error('Failed to obtain the cause of the failure');
    }finally {
      hideLoading();
    }
  }
  const getCountry = async() => {
    showLoading('loading country...')
    try {
      const res = await axios.get(`${BASE_URL}manage/selectCountry`)
      countryList.value = res.data.data
    }catch(error) {

    }finally{
      hideLoading();
    }
  }
  //添加方法
  const handleAdd =() => {
    dialogTitle.value = 'Add data';
    dialogVisible.value = true;
  }
  const handleConfirm = async() => {
    if(!formData.value.model) {
      ElMessage.warning('Please select the model');
      return;
    }else if(!formData.value.nickName){
      ElMessage.warning('Please enter the name');
      return;
    }else if(!formData.value.account){
      ElMessage.warning('Please enter your account number');
      return;
    }else if(!formData.value.faultPart || formData.value.faultPart.length === 0) {
      ElMessage.warning('Please select the faulty component');
      return;
    }else if(!formData.value.reason || formData.value.reason.length === 0) {
      ElMessage.warning('Please select the cause of the failure');
      return;
    }
    const base64Account = btoa(unescape(encodeURIComponent(formData.value.account)));
    const submitData = {
      ...formData.value,
      account: base64Account,
      faultPart: formData.value.faultPart.join(','),
      faultType: selectedFaultTypes.value.join(','), 
      reason: formData.value.reason.join(','),
      images: formData.value.images? formData.value.images.join(',') : '',
    };

    try {
      showLoading('Submitting data...');
      const res = await axios.post(`${BASE_URL}afterSales/add`,submitData,{
        headers:{
          'Content-Type': 'application/json',
        },
      })
      if(res.data.code === 0){
        ElMessage.success('Added successfully:');
        dialogVisible.value = false;
        resetForm();
      await fetchData();  // 重新加载数据
      }
    }catch(error) {
      ElMessage.error('Addition failed: ' + error.msg);
    }finally {
      hideLoading();
    }
  }
  // 重置表单
  const resetForm = () => {
    formData.value = {
      model: '',
      dealer: dealer.value,
      userId: '4a0779520f65448f8ca5386b0aec15ff',
      city: '',
      faultPart: [],
      reason: [],
      partMissing: '',
      images: []
    };
    faultPartsOptions.value = [];
    reasonsOptions.value = [];
    images.value = [];
    selectedParts.value = [];
    selectedFaultTypes.value = [];
  }
  //删除方法
  const handleDelete = async(index) => {
    try {
      showLoading('Deleting...');
      const userToDelete = tableData.value[index];
      await axios.delete(`${BASE_URL}manage/delAfterSale/${userToDelete.id}`)
      tableData.value.splice(index, 1);
      ElMessage.success('Deletion was successful');
    } catch(error) {
      ElMessage.error('Deletion failed:',error.msg);
    } finally {
      hideLoading();
    }
  };

  // 计算当前页显示的数据
  const currentTableData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return tableData.value.slice(start, end);
  });
  // 当前页改变
  const handleCurrentChange = (val) => {
    currentPage.value = val;
  };

  //跳转修改内容
  function showUserDetails(row) {
    selectedUser.value = row;
    showDetails.value = true;
  }
  function handleBack() {
    showDetails.value = false;
  }
  //获取订单状态
  function handleStatusUpdated({id,state}){
    // 更新tableData中对应的记录
    const index = tableData.value.findIndex(item => item.id === id);
    if (index !== -1 ){
      tableData.value[index].state = state;
    }
    // 如果当前正在查看的就是这条记录，也更新selectedUser
    if (selectedUser.value && selectedUser.value.id === id){
      selectedUser.value.state = state;
    }
  }
  
  // 图片上传
  const onFileChange = async (e, index) => {
    const file = e.target.files[0];
    if (!file) return;

    try {
      showLoading('Uploading image...');
      // 压缩图片
      const compressedFile = await compressImg(file);
      
      // 创建 FormData 用于上传
      const uploadFormData = new FormData();
      uploadFormData.append('multipartFile', compressedFile);
      uploadFormData.append('fileName', `${Date.now()}.jpg`);

      // 上传图片
      const res = await axios.post(`${BASE_URL}upload/file`, uploadFormData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      });
      
      if (res.data.code === 0) {
        const  url  = res.data.data.url;
        
        // 确保 images 数组有足够长度
      if (!formData.value.images) {
        formData.value.images = [];
      }
      
      // 更新或添加图片信息
      formData.value.images[index] = url; 
      
      // 更新预览图片
      if (!images.value[index]) {
        images.value.push({ src: url });
      } else {
        images.value[index] = { src: url };
      }
        
      }
    } catch (error) {
      ElMessage.error('The picture upload failed');
    } finally {
      hideLoading();
    }
  };
  // 图片删除
  const onImageDel = async (index)=> {
    if (key) {
      try {
        showLoading('Deleting image...');
        const key = images.value[index]?.key;
        await axios.post(`${BASE_URL}file/del`, null, {
          params: { fileKey: key }
        });
        if (!Array.isArray(formData.value.images)) {
        formData.value.images = [];
      }
        // 从 images 和 formData 中移除对应的图片
        images.value.splice(index, 1);
        formData.value.images.splice(index, 1);
      } catch (error) {
        ElMessage.error('The deletion of the picture failed');
      } finally{
        hideLoading();
      }
    } else {
      // 如果是本地未上传的图片
      images.value.splice(index, 1);
      if (Array.isArray(formData.value.images) && index < formData.value.images.length) {
        formData.value.images.splice(index, 1);
      }
    }
  }

  // 格式化日期部分
  const formatDate = (datetime) => {
    if (!datetime) return '';
    return new Date(datetime).toLocaleDateString();
    // 或者使用更具体的格式：
    // return datetime.split(' ')[0];
  };

  // 格式化时间部分
  const formatTime = (datetime) => {
    if (!datetime) return '';
    return new Date(datetime).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
    // 或者使用更简单的格式：
    // return datetime.split(' ')[1]?.substring(0, 5);
  };

  const cellStyle = ({ column }) => {
  if (['model', 'faultPart', 'state'].includes(column.property)) {
    return { backgroundColor: '#f5f5f5' }
  }
  return {}
}

const headerCellStyle = ({ column }) => {
  if (['model', 'faultPart', 'state'].includes(column.property)) {
    return {
      backgroundColor: '#f5f5f5',
      color: 'rgb(82,85,96)'
    }
  }
  return { color: 'rgb(82,85,96)' }
}
</script>

<style scoped>
  .paren {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 180px);
    box-sizing: border-box;
    background-color: white;
    color: black;
  }
  .table-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    margin-bottom: 10px;
  }
  /* 固定表头样式 */
  :deep(.el-table__header-wrapper) {
    position: sticky;
    top: 0;
    z-index: 10;
  }
  /* 表格滚动区域 */
  :deep(.el-table__body-wrapper) {
    overflow-y: auto;
    flex: 1;
  }
  
  /* 表格全局居中样式 */
  :deep(.el-table .el-table__cell) {
    text-align: center;
    height: 80px;
    font-size: 20px;
    padding: 0 25px;
  }
  :deep(.el-table .el-table__cell .cell) {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 150px;
  }
  .datetime-cell {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    line-height: 1.3;
  }

  .date-part {
    font-size: 20px;
    margin-bottom: 2px;
  }

  .time-part {
    font-size: 18px;
    color: #666;
  }
  :deep(.el-table .el-button) {
    font-size: 18px;
    width: 80px;
    height: 35px;
    background-color: #409eff;
    color: white;
    border: none;
    border-radius: 8px;
    }
  :deep(.el-table .el-button:hover) {
    background-color: #66b1ff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  }
  :deep(.el-table .el-button:active) {
    transform: scale(0.98);
  }
  /* 固定底部分页 */
  .pagination-footer {
    flex-shrink: 0;
    padding: 18px 50px 18px 100px;
    display: flex;
    justify-content: flex-end;
    color: rgb(79, 83, 79);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); /* 标准阴影 */
  }
  :deep(.el-pagination),
  :deep(.el-pagination .number),
  :deep(.el-pagination .el-input__inner),
  :deep(.el-pagination__total),
  :deep(.el-pagination__sizes) {
    font-size: 20px;
  }
  .add-button {
    display: flex;
    justify-content: flex-end;
    margin-left: 30px;
  }
  :deep(.add-button .el-button){
    font-size: 20px;
    width: 80px;
    height: 40px;
    border-radius: 10px;
  }
  :deep(.large-dialog .el-form-item__label),
  :deep(.large-dialog .el-input__inner) {
    /* width: 18%; */
    height: 40px !important;
    font-size: 18px !important;
    line-height: 40px !important;
  }
  /* 表单行布局 */
  .form-row {
    display: flex;
    gap: 16px; /* 字段间距 */
  }

  /* 通用表单项样式 */
  .el-form-item {
    flex: 1;
  }
  /* 半宽字段（如 model 和 dealer） */
  .form-item-half {
    flex: 0 0 calc(50% - 8px); /* 50% 宽度，减去间隙 */
  }
  /* 2/3 宽度字段（country 和 account） */
  .form-item-two-thirds {
    flex: 0 0 calc(66.66% - 8px);
  }
  /* 1/3 宽度字段（city 和 name） */
  .form-item-one-third {
    flex: 0 0 calc(33.33% - 8px);
  }
  /* 调整下拉框和输入框宽度 */
  .el-select, .el-input {
    width: 100%;
  }
  /* 多选下拉框样式优化 */
  :deep(.el-select__tags) {
    max-height: 60px;
    overflow-y: auto;
    flex-wrap: wrap;
  }
  /* 禁用状态样式 */
  :deep(.el-select.is-disabled .el-select__tags) {
    background-color: #f5f7fa;
  }
  :deep(.dialog-footer .el-button) {
    font-size: 20px;
    padding: 12px 24px;
    height: 38px;
    width: 80px;
    margin-left: 20px;
  }
  .upload-img-btn {
    position: relative;
    display: flex;
    justify-content: space-around;
    margin: 0 auto;
    margin-top: 5px;
    margin-left: 15px;
    margin-right: 10px;
  }
  .img-scan {
    position: absolute;
    width: 90%;
    height: 90%;
    bottom: 0;
    left: 0;
    z-index: 1;
  }
  .upload-input {
    position: absolute;
    width: 90%;
    height: 90%;
    bottom: 0;
    left: 0;
    outline: none;
    cursor: pointer;
    opacity: 0;
    z-index: 2;
  }
  .img-del{
    position: absolute;
    width: 25px;
    height: 25px;
    top: 0;
    right: 0;
    cursor: pointer;
    z-index: 3;
  }
  .el-form-item.is-required .el-form-item__label::before {
    color: red;
  }
</style>